import React, { useEffect, useRef, useState } from 'react'
import type { FC, ReactNode } from 'react'
import { memo } from 'react'
import { NavBar, SearchBar, Button } from 'antd-mobile'
import { EnvironmentOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'
import { SearchBarRef } from 'antd-mobile/es/components/search-bar'
import MyMap from './style'

interface Iprops {
  children?: ReactNode
}

const Map: FC<Iprops> = () => {
  const navigate = useNavigate()
  const searchRef = useRef<SearchBarRef>(null)
  const mapRef = useRef<any>(null) // ✅ 存地图实例
  const cityRef = useRef<string>('') // ✅ 存当前城市
  const [inputValue, setInputValue] = useState('')

  // 地图初始化（仅执行一次）
  useEffect(() => {
    if (!window.BMap) {
      console.error('BMap 未加载，请检查 index.html 中是否引入百度地图脚本')
      return
    }

    // 创建地图实例
    const map = new window.BMap.Map('map')
    mapRef.current = map

    const defaultPoint = new window.BMap.Point(116.404, 39.915)
    map.centerAndZoom(defaultPoint, 13)
    map.enableScrollWheelZoom(true)

    // 获取当前城市并设置中心
    const myCity = new window.BMap.LocalCity()
    myCity.get((result: any) => {
      const cityName = result.name
      cityRef.current = cityName
      map.setCenter(cityName)
      console.log('当前定位城市:', cityName)

      // 初始显示该城市医院
      const local = new window.BMap.LocalSearch(map, {
        renderOptions: { map, autoViewport: true }
      })
      local.search(`${cityName}医院`)
    })
  }, [])

  // 搜索功能
  const handleSearch = () => {
    const map = mapRef.current
    const cityName = cityRef.current

    if (!map || !cityName) {
      console.warn('地图或城市未初始化')
      return
    }

    const local = new window.BMap.LocalSearch(map, {
      renderOptions: { map, autoViewport: true }
    })

    const keyword = inputValue.trim() || '医院'
    local.search(`${cityName}${keyword}`)
  }

  const back = () => navigate(-1)

  // 定位按钮
  const handleLocate = () => {
    const map = mapRef.current
    if (!map) return

    const geolocation = new window.BMap.Geolocation()

    geolocation.getCurrentPosition((r: any) => {
      if (geolocation.getStatus() === window.BMAP_STATUS_SUCCESS) {
        const mk = new window.BMap.Marker(r.point)
        map.addOverlay(mk)
        map.panTo(r.point)
        console.log('当前位置：', r.point)
      } else {
        alert('定位失败')
      }
    })
  }

  return (
    <MyMap>
      <NavBar onBack={back}>医院地图</NavBar>

      <div
        className="search"
        style={{ display: 'flex', alignItems: 'center', padding: '5px' }}
      >
        <Button size="mini" color="primary" onClick={handleLocate}>
          <EnvironmentOutline />
        </Button>

        <SearchBar
          placeholder="输入医院或药店名称"
          ref={searchRef}
          value={inputValue}
          onChange={setInputValue}
          style={{ flex: 1, margin: '0 5px' }}
        />

        <Button size="mini" color="primary" onClick={handleSearch}>
          搜索
        </Button>
      </div>

      <div
        id="map"
        style={{ width: '100%', height: 'calc(100vh - 45px)' }}
      ></div>
    </MyMap>
  )
}

export default memo(Map)
